import 'package:dio/dio.dart';
import 'package:fusion_one/redux/store/index.dart';

class RequestBase {
  bool success;
  dynamic resultInfo; // 数据
  RequestBase({required this.success, required this.resultInfo});

  factory RequestBase.fromJson(Map<String, dynamic> json) {
    return RequestBase(
        success: json["success"], resultInfo: json["resultInfo"]);
  }
}

// 封装dio
class DioUtils {
  static Dio? _dio;
  static const String BASE_URL = "https://gw.fusionalign.com";
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 30000;

  DioUtils() {
    if (_dio == null) {
      _dio = Dio();
      _dio!.options.baseUrl = BASE_URL;
      _dio!.options.connectTimeout = CONNECT_TIMEOUT;
      _dio!.options.receiveTimeout = RECEIVE_TIMEOUT;
      _dio!.options.headers = {
        "Content-Type": "application/json",
      };
      _dio!.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["Authorization"] =
              "Bearer ${store.state.token!.access_token}";
          print("发送请求：${options.uri}");
          return handler.next(options);
        },
        onResponse: (response, handler) {
          print("收到请求：${response.requestOptions.uri}");
          return handler.next(response);
        },
      ));
    }
  }

  Future<RequestBase> get(String url,
      {Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelToken}) async {
    Response response;
    try {
      response = await _dio!.get(url,
          queryParameters: params, options: options, cancelToken: cancelToken);
    } on DioError catch (e) {
      rethrow;
    }
    return RequestBase.fromJson(response.data);
  }

  Future<RequestBase> post(String url,
      {Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelToken}) async {
    Response response;
    try {
      response = await _dio!
          .post(url, data: params, options: options, cancelToken: cancelToken);
    } on DioError catch (e) {
      throw e;
    }
    return RequestBase.fromJson(response.data);
  }

  Future<RequestBase> put(String url,
      {Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelToken}) async {
    Response response;
    try {
      response = await _dio!
          .put(url, data: params, options: options, cancelToken: cancelToken);
    } on DioError catch (e) {
      throw e;
    }
    return RequestBase.fromJson(response.data);
  }

  Future<RequestBase> delete(String url,
      {Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelToken}) async {
    Response response;
    try {
      response = await _dio!.delete(url,
          data: params, options: options, cancelToken: cancelToken);
    } on DioError catch (e) {
      throw e;
    }
    return RequestBase.fromJson(response.data);
  }
}
